﻿using System;
using System.Data;

namespace PublicDomain.Data.Csv
{
    public class CsvConnection : IDbConnection
    {
        private CsvConnectionStringBuilder connectionStringBuilder;
        private ConnectionState state = ConnectionState.Closed;

        public CsvConnection(string connectionString)
        {
            this.connectionStringBuilder = new CsvConnectionStringBuilder(connectionString);
        }

        public CsvConnection()
            : this(String.Empty)
        {
        }

        public string ConnectionString
        {
            get { return this.connectionStringBuilder.ConnectionString; }
            set { this.connectionStringBuilder.ConnectionString = value; }
        }

        public string Database
        {
            get { return this.connectionStringBuilder.Database; }
        }

        public ConnectionState State
        {
            get { return this.state; }
        }

        public int ConnectionTimeout
        {
            get { return -1; }
        }

        public char? Delimiter
        {
            get { return this.connectionStringBuilder.Delimiter; }
            set { this.connectionStringBuilder.Delimiter = value; }
        }

        public int? HeaderRowsCount
        {
            get { return this.connectionStringBuilder.HeaderRowsCount; }
            set { this.connectionStringBuilder.HeaderRowsCount = value; }
        }

        public string SchemataFilePath
        {
            get { return this.connectionStringBuilder.SchemataFilePath; }
            set { this.connectionStringBuilder.SchemataFilePath = value; }
        }

        public CsvParsingOptions ParsingOptions
        {
            get { return this.connectionStringBuilder.ParsingOptions; }
            set { this.connectionStringBuilder.ParsingOptions = value; }
        }

        public void Open()
        {
            this.state = ConnectionState.Open;
        }

        public void Close()
        {
            this.state = ConnectionState.Closed;
        }

        public IDbCommand CreateCommand()
        {
            var result = new CsvCommand(String.Empty, this);
            return result;
        }

        public void ChangeDatabase(string databaseName)
        {
            this.connectionStringBuilder.Database = databaseName;
        }

        public IDbTransaction BeginTransaction(IsolationLevel il)
        {
            throw new NotImplementedException();
        }

        public IDbTransaction BeginTransaction()
        {
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.Close();
            }
        }
    }
}
